//
//  ZiChanViewController.m
//  marrymarry
//
//  Created by lsj on 16/9/26.
//  Copyright © 2016年 cf. All rights reserved.
//
static NSString * sendPhotoCellID  = @"sendPhotoTableViewCell";
#import "ZiChanViewController.h"
#import "sendPhotoTableViewCell.h"
#import "ZichanView.h"
#import "saveFootView.h"
@interface ZiChanViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    NSDictionary * carDic;
    NSDictionary * buyCarDic;
    NSDictionary * houseDic;
    NSMutableArray * _myPicArry;
    UIImage * _carImg;
    UIImage * _buyCarImg;
    UIImage * _houseImg;
    NSString * _carImg_Url;
    NSString * _buyCarImg_Url;
    NSString * _houseImg_Url;
    NSString * _getWhatInfoUrl;
    BOOL _isOnChecking;
    BOOL _isPassed;
    BOOL _isfailed;
}
@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@property (strong , nonatomic) ZichanView * zichanHeadView;
@property (nonatomic,strong) NSMutableArray * dataArry;
@property (strong, nonatomic) saveFootView * footView;


@property (nonatomic, strong) NSArray<ZLSelectPhotoModel *> *lastSelectMoldels;
@property (nonatomic, strong) NSArray *arrDataSources;
@property (nonatomic,strong) NSArray * MyPicStrArry;
@property (strong , nonatomic) NSArray * selectPicArry;
@end

@implementation ZiChanViewController
///选择存储img的数组
-(NSArray *)selectPicArry
{
    if (!_selectPicArry) {
        _selectPicArry = [NSArray new];
    }
    return _selectPicArry;
}


-(NSMutableArray*)dataArry
{
    if (!_dataArry) {
        if(self.ishouse)
        {
            _dataArry = [[NSMutableArray alloc]initWithArray:@[@"1"]];
        }else
        {
            _dataArry = [[NSMutableArray alloc]initWithArray:@[@"1",@"2"]];
        }
        
        
    }
    return _dataArry;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupHeadView];
    NSLog(@"self.ishouse ======  %d",self.ishouse);
    _myPicArry = [NSMutableArray new];
    [self setupTableViewFootView];
    
    if (self.ishouse) {
        _getWhatInfoUrl = WATCHHOUSE_URL;
       
    }else{
        _getWhatInfoUrl = WATCHCAR_URL;
    }
    [self requestTheNetWith:nil andURL:_getWhatInfoUrl andDic:@{@"id":[Tools getValueFromNSUserDefaultsByKey:USERID]}];
    
}
-(void)setupTableViewFootView
{
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.myTableView.frame.size.width, 80)];
    self.myTableView.tableFooterView = footView;
    self.footView = [[[NSBundle mainBundle] loadNibNamed:@"saveFootView" owner:self options:nil] lastObject];
    self.footView.frame = CGRectMake(0, 0,self.myTableView.frame.size.width,80);
    [footView addSubview: self.footView];
    
    self.footView.saveFootBtn.layer.cornerRadius = 5;
    [self.footView.saveFootBtn addTarget:self action:@selector(pushMyPhoto) forControlEvents:UIControlEventTouchUpInside];
    
}


-(void)pushMyPhoto
{
    if (self.ishouse) {
        if (_houseImg!= nil) {
            [self requestTheNetWith:self.selectPicArry andURL:UPDATEHOUSE_URL andDic:@{@"id":[Tools getValueFromNSUserDefaultsByKey:USERID]}];
        }
    }else{
        if (_carImg != nil && _buyCarImg !=nil) {
            [self requestTheNetWith:self.selectPicArry andURL:UPDATECAR_URL andDic:@{@"id":[Tools getValueFromNSUserDefaultsByKey:USERID]}];
        }else
        {
            [SVProgressHUD showErrorWithStatus:@"请选择照片"];
        }
    }
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.hidesBottomBarWhenPushed = YES;
}
-(void)setupHeadView
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.myTableView.frame.size.width, 60)];
    self.myTableView.tableHeaderView = headerView;

     self.zichanHeadView = [[[NSBundle mainBundle] loadNibNamed:@"ZichanView" owner:self options:nil] lastObject];
    self.zichanHeadView.frame = CGRectMake(0,0,self.myTableView.frame.size.width, 60);
    [headerView addSubview:self.zichanHeadView];
    if (self.ishouse) {
        self.zichanHeadView.headViewLabel.text = @"以结婚为目的交往,住房问题是对方关心的,我要上传房产证或者购房合同进行资产认证";
    }
    [self.myTableView reloadData];
    
}
#pragma mark UITableViewDatasource,UITableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
  
    return  1;
    
    
    
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.ishouse) {
        return 1;
    }else
    {
        return 2;
    }

}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
        sendPhotoTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:sendPhotoCellID];
        if (!cell) {
            cell = [[sendPhotoTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:sendPhotoCellID];
        }
    
    [cell reloadTheViewWith:self.dataArry andNSindexPath:indexPath andisHouse:self.ishouse];
    cell.rightAddImgView.userInteractionEnabled = YES;
    if (self.ishouse) {
        
        if (_houseImg != nil || _houseImg_Url !=nil) {
            if (_isOnChecking||_isPassed) {
                cell.deleBtn.hidden= YES;
                cell.rightAddImgView.userInteractionEnabled = NO;
            }else{
             cell.deleBtn.hidden = NO;
                  cell.rightAddImgView.userInteractionEnabled = YES;
            }
            cell.deleBtn.tag = 3;
            [cell.deleBtn addTarget:self action:@selector(deletImgBtn:) forControlEvents:UIControlEventTouchUpInside];
            if (_houseImg_Url != nil) {
                [cell.rightAddImgView setImageWithURL:[NSURL URLWithString:_houseImg_Url]];
            }else{
            [cell.rightAddImgView setImage:_houseImg];
            }
        }else{
            cell.deleBtn.hidden = YES;
            [cell.rightAddImgView setImage:[UIImage imageNamed:@"tianjia.jpg"]];
            CFUITapGestureRecognizer * myTap = [[CFUITapGestureRecognizer alloc]initWithTarget:self action:@selector(addphotoWithTap:)];
            myTap.usertype = @"3";
            [cell.rightAddImgView addGestureRecognizer:myTap];
        }
        
    }else
    {
        if (indexPath.row == 0) {
            if (_carImg != nil||_carImg_Url!=nil) {
                if (_carImg_Url != nil) {
                    [cell.rightAddImgView setImageWithURL:[NSURL URLWithString:_carImg_Url]];
                }else{
                [cell.rightAddImgView setImage:_carImg];
                }
                if (_isOnChecking||_isPassed) {
                    cell.deleBtn.hidden= YES;
                    cell.rightAddImgView.userInteractionEnabled = NO;
                }else{
                    cell.deleBtn.hidden = NO;
                      cell.rightAddImgView.userInteractionEnabled = YES;
                }
                cell.deleBtn.tag = 1;
                [cell.deleBtn addTarget:self action:@selector(deletImgBtn:) forControlEvents:UIControlEventTouchUpInside];
            }else{
                  cell.deleBtn.hidden = YES;
                CFUITapGestureRecognizer * myTap = [[CFUITapGestureRecognizer alloc]initWithTarget:self action:@selector(addphotoWithTap:)];
                myTap.usertype = @"1";
                [cell.rightAddImgView addGestureRecognizer:myTap];
                [cell.rightAddImgView setImage:[UIImage imageNamed:@"tianjia.jpg"]];
            }
            
        }else{
            if (_buyCarImg != nil|| _buyCarImg_Url != nil) {
                if (_buyCarImg_Url != nil) {
                    [cell.rightAddImgView setImageWithURL:[NSURL URLWithString:_buyCarImg_Url]];
                }else{
                [cell.rightAddImgView setImage:_buyCarImg];
                }
                if (_isOnChecking||_isPassed) {
                    cell.deleBtn.hidden= YES;
                    cell.rightAddImgView.userInteractionEnabled = NO;
                }else{
                    cell.deleBtn.hidden = NO;
                    cell.rightAddImgView.userInteractionEnabled = YES;
                }
                cell.deleBtn.tag = 2;
                [cell.deleBtn addTarget:self action:@selector(deletImgBtn:) forControlEvents:UIControlEventTouchUpInside];
            }else
            {
                 cell.deleBtn.hidden = YES;
                CFUITapGestureRecognizer * myTap = [[CFUITapGestureRecognizer alloc]initWithTarget:self action:@selector(addphotoWithTap:)];
                myTap.usertype = @"2";
                [cell.rightAddImgView addGestureRecognizer:myTap];
                [cell.rightAddImgView setImage:[UIImage imageNamed:@"tianjia.jpg"]];
            }
            
        }
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
   
    return 190;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
}


-(void)deletImgBtn:(UIButton * )deleBtn
{
    if (deleBtn.tag == 1) {
        _carImg = nil;
        _carImg_Url = nil;
    }else if (deleBtn.tag ==2)
    {
        _buyCarImg = nil;
        _buyCarImg_Url = nil;
    }else
    {
        _houseImg = nil;
        _houseImg_Url = nil;
    }
    [self.myTableView reloadData];
}




///添加照片
-(void)addphotoWithTap:(CFUITapGestureRecognizer * )myTap
{
    
    ZLPhotoActionSheet *actionSheet = [[ZLPhotoActionSheet alloc] init];
    //设置照片最大选择数
    actionSheet.maxSelectCount = 1;
    //设置照片最大预览数
    actionSheet.maxPreviewCount = 20;
    actionSheet.isInVC = YES;
    weakify(self);
    [actionSheet showWithSender:self animate:YES lastSelectPhotoModels:self.lastSelectMoldels completion:^(NSArray<UIImage *> * _Nonnull selectPhotos, NSArray<ZLSelectPhotoModel *> * _Nonnull selectPhotoModels) {
        strongify(weakSelf);
        strongSelf.arrDataSources = selectPhotos;
        strongSelf.lastSelectMoldels = selectPhotoModels;
        NSLog(@"%@", selectPhotos);
        self.selectPicArry = strongSelf.arrDataSources;

        /** 如果等于1 选择的是行驶证 如果等于2 选择的是购车合同 如果等于3 选择的是房产证 **/
        if ([myTap.usertype isEqualToString:@"1"]) {
            _carImg = self.selectPicArry[0];
        }else if ([myTap.usertype isEqualToString:@"2"]){
            _buyCarImg = self.selectPicArry[0];
        }else{
            _houseImg = self.selectPicArry[0];
        }
        [self.myTableView reloadData];
    }];
   
}
-(void)imgbig:(CFUITapGestureRecognizer*)imgTap
{
    [ZLShowBigImage showBigImage:imgTap.tapImgView];
}


#pragma mark --------------网络请求
-(void)requestTheNetWith:(NSArray *)myRequestArry andURL:(NSString *)myurl andDic:(NSDictionary *)myDic;
{
    
     [_myPicArry removeAllObjects];
    
    if (myRequestArry.count>0) {
        if (self.ishouse) {
            houseDic = @{@"imgname":@"houseimg",@"pic":_houseImg};
             [_myPicArry addObject:houseDic];
        }else{
            
        carDic = @{@"imgname":@"drivingimg",@"pic":_carImg};
        buyCarDic = @{@"imgname":@"contractimg",@"pic":_buyCarImg};
        [_myPicArry addObject:carDic];
        [_myPicArry addObject:buyCarDic];
        }
        [[LJFNetworkingManager shareManager] POST:myurl upLoadImages:_myPicArry parameters:myDic success:^(id returnData, int code, NSString *msg) {
            NSLog(@"%@",msg);
            if (code == 1) {
                [SVProgressHUD showSuccessWithStatus:@"上传成功"];
                [self.footView.saveFootBtn setTitle:@"正在审核" forState:UIControlStateNormal];
                self.footView.saveFootBtn.userInteractionEnabled = NO;
                self.footView.saveFootBtn.backgroundColor = [UIColor lightGrayColor];
                _isOnChecking = YES;
                [self.myTableView reloadData];
            }
        
        } failure:^(NSError *error) {
            NSLog(@"失败");
         
        } showHUD:nil];
        [self.myTableView reloadData];
    }else
    {
        [[LJFNetworkingManager shareManager] POST:myurl parameters:myDic success:^(id returnData, int code, NSString *msg) {
            NSLog(@"%@",msg);
            if (self.ishouse) {
                if (code == 1) {
                    NSLog(@"%@",returnData);
                    _houseImg_Url = returnData[@"deedPhoto"];
                    if ([returnData[@"status"] intValue] == 0) {
                        _isOnChecking = YES;
                        [self setFootViewBtn];
                    }else if ([returnData[@"status"] intValue] == 1)
                    {
                        _isPassed = YES;
                        [self setFootViewBtn];
                    }
                    else if ([returnData[@"status"] intValue] == 2)
                    {
                        _isfailed = YES;
                        [self setFootViewBtn];
                    }
                    else{
                        _isOnChecking = NO;
                    }
                    
                }
            }else{
                if (code == 1) {
                    NSLog(@"%@",returnData);
                    _carImg_Url = returnData[@"drivingLicence"];
                    _buyCarImg_Url = returnData[@"contractPhoto"];
                    if ([returnData[@"status"] intValue] == 0) {
                        _isOnChecking = YES;
                        [self setFootViewBtn];
                    }else if ([returnData[@"status"] intValue] == 1)
                    {
                        _isPassed = YES;
                        [self setFootViewBtn];
                    }
                    else if ([returnData[@"status"] intValue] == 2)
                    {
                        _isfailed = YES;
                        [self setFootViewBtn];
                    }
                    else{
                        _isOnChecking = NO;
                    }
                }
            }
            [self.myTableView reloadData];
            
        } failure:^(NSError *error) {
            NSLog(@"%@",error);
        } showHUD:self.view];
        
    }
    
    
}



-(void)setFootViewBtn
{
    if (_isOnChecking) {
        [self.footView.saveFootBtn setTitle:@"正在审核" forState:UIControlStateNormal];
        self.footView.saveFootBtn.userInteractionEnabled = NO;
        self.footView.saveFootBtn.backgroundColor = [UIColor lightGrayColor];
    }else if(_isPassed)
    {
        [self.footView.saveFootBtn setTitle:@"审核通过" forState:UIControlStateNormal];
        self.footView.saveFootBtn.userInteractionEnabled = NO;
        self.footView.saveFootBtn.backgroundColor =RGB(0, 234, 202);
    }else if (_isfailed)
    {
        [self.footView.saveFootBtn setTitle:@"审核不通过" forState:UIControlStateNormal];
        self.footView.saveFootBtn.userInteractionEnabled = YES;
        self.footView.saveFootBtn.backgroundColor =RGB(0, 234, 202);
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
